Ext.define('SRMT.controller.Viewport', {
	extend: 'Ext.app.Controller',
	
	views: ['Viewport'],
	
	refs: [
	{
		ref: 'viewport',
		selector: 'viewport'
	},{
		ref: 'northPanel',
		selector: 'viewport > #north-panel'
	},{
		ref: 'westPanel',
		selector: 'viewport > #west-panel'
	},{
		ref: 'eastPanel',
		selector: 'viewport > #east-panel'
	},{
		ref: 'centerPanel',
		selector: 'viewport > #center-panel'
	}],
	
	init: function() {
		this.control({
			'viewport': {
				render: this.onRender
			},
			
			'viewport > #north-panel': {
				render: this.onNorthPanelRender
			},
			
			'viewport > #west-panel': {
				render: this.onWestPanelRender
			},
			
			'viewport > #east-panel': {
				render: this.onEastPanelRender
			},
			
			'viewport > #center-panel': {
				render: this.onCenterPanelRender
			}
			
		})
	},
	
	onRender: function() {
		var menuController = this.getController('SRMT.controller.Menu');
		var projectExplorerController = this.getController('SRMT.controller.project-explorer.ProjectExplorer');
		
		if(this.isLogin()) {
			menuController.setMenuLogin();
			this.getWestPanel().setVisible(true);
			this.getEastPanel().setVisible(true);
			this.getStore('SRMT.store.ProjectExplorer').load();
			
		} else {
			menuController.setMenuLogout();
			this.getWestPanel().setVisible(false);
			this.getEastPanel().setVisible(false);
			this.getCenterPanel().removeAll(true);
		}
		var aboutTab = Ext.create('SRMT.view.About', {itemId: '0', closable: true});
		this.addTabToCenterPanel(aboutTab);
	},
	
	onNorthPanelRender: function() {
		
	},
	
	onCenterPanelRender: function() {
		
	},
	
	onWestPanelRender: function() {
		
	},
	
	onEastPanelRender: function() {
		
	},
	
	setViewportEnable: function() {
		this.getNorthPanel().enable();
		this.getWestPanel().enable();
		this.getEastPanel().enable();
		this.getCenterPanel().enable();
	},
	
	setViewportDisable: function() {
		this.getNorthPanel().disable();
		this.getWestPanel().disable();
		this.getEastPanel().disable();
		this.getCenterPanel().disable();
	},
	
	addTabToCenterPanel: function(tab) {
		if(this.getCenterPanel().child('#'+tab.getItemId()) == null) {
			this.getCenterPanel().add(tab);
		}
		this.getCenterPanel().setActiveTab(tab);
	},
	
	isLogin: function() {
		var request = Ext.Ajax.request({
			url: 'php/module/authenticate/islogin.php',
			async: false,
			waitMsg: 'Loading ...',
			timeout: 5000,
			failure: function(response) {
				Ext.MessageBox.show({
					title: 'Error',
					msg: 'Check login failed!',
					buttons: Ext.MessageBox.OK,
					icon: Ext.MessageBox.ERROR
				});
			}
		});
		
		return Ext.JSON.decode(request.responseText).islogin;
	}
});